package com.meitianhui.convenitenbuy.module.home.ui.activity.web;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebView;

import com.ali.auth.third.ui.context.CallbackContext;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.context.AlibcResultType;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.HomeOrderActivity;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.NoScrollWebView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/4.
 */

public class AliSdkWebViewProxyActivity extends BaseToolbarActivity {
    private NoScrollWebView mWebView;


    private String mOrderId;
    private String mTaoBaoLink;


    @Override
    protected int setView() {
        return R.layout.activity_alsdk_webview;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mWebView = getViewById(R.id.web_view);
        setTbTitle("淘淘领");
        setTbMenu(R.mipmap.icon_title_close);
        initData();

    }


    private void initData() {
        Intent intent = this.getIntent();
        mOrderId = intent.getStringExtra("order_id");
        mTaoBaoLink = intent.getStringExtra("taobao_link");
        if(TextUtils.isEmpty(mOrderId)){
            RxView.visibility(getViewById(R.id.ll_go_buy)).call(false);
            RxView.visibility(getViewById(R.id.tv_go_order)).call(true);
            RxTextView.text(getViewById(R.id.tv_go_order)).call("如果中意该商品，请回退点击立即领取按钮下单支付");
        }
        if(TextUtils.isEmpty(mTaoBaoLink)) {
            TipUtils.showToast(App.getInstance(),"获取淘宝链接失败", 2);
        }
        showUrl();
    }

    @Override
    protected void clickMenu() {
        super.clickMenu();
        finish();
    }

    //打开淘宝链接
    private void showUrl() {
        Map<String, String> exParams = new HashMap<>();
        exParams.put("isv_code", mOrderId);//isvcode 上传订单号
        AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams("mm_26632322_6858406_23810104", "mm_26632322_6858406_23810104", null); // 若非淘客taokeParams设置为null即可
        //  AlibcBasePage alibcBasePage = new AlibcDetailPage("557128118253");//电力1毛钱商品
        AlibcShowParams alibcShowParams = new AlibcShowParams(OpenType.H5, false);
//        AlibcTrade.show(AliSdkWebViewProxyActivity.this,webView, null, null,alibcBasePage,alibcShowParams,alibcTaokeParams,exParams, new DemoTradeCallback());
        //测试商品 杯子5毛钱
        //String url="https://item.taobao.com/item.htm?id=560289970376&ali_trackid=2:mm_126467918_37382097_136386620:1508468696_201_1798096987&pvid=10_116.30.220.255_545_1508408568318";
        AlibcTrade.show(AliSdkWebViewProxyActivity.this, mWebView, new WebViewClient(), null, new AlibcPage(mTaoBaoLink), alibcShowParams, alibcTaokeParams, exParams, new DemoTradeCallback());
        refreshFinish();
    }

    @Override
    protected void onRefreshData() {
        showUrl();
    }

    public class WebViewClient extends android.webkit.WebViewClient {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String s_url) {
            if (s_url.contains("addressList")) {
                //地址选择页
                isEnable(false);
            } else {
                isEnable(true);
            }

            if (!TextUtils.isEmpty(mOrderId)) {
                if (s_url.contains("order.html")) {
                    //跳到订单页面
                    RxView.visibility(getViewById(R.id.ll_go_buy)).call(false);
                    RxView.visibility(getViewById(R.id.tv_go_order)).call(true);
                } else {
                    RxView.visibility(getViewById(R.id.ll_go_buy)).call(true);
                    RxView.visibility(getViewById(R.id.tv_go_order)).call(false);

                }
            }

        }
    }

    public class DemoTradeCallback implements AlibcTradeCallback {

        @Override
        public void onTradeSuccess(AlibcTradeResult tradeResult) {
            //当addCartPage加购成功和其他page支付成功的时候会回调

            if (tradeResult.resultType.equals(AlibcResultType.TYPECART)) {
                //加购成功
                //   Toast.makeText(AliSdkWebViewProxyActivity.this, "加购成功", Toast.LENGTH_SHORT).show();
            } else if (tradeResult.resultType.equals(AlibcResultType.TYPEPAY)) {
                Log.i("mylog", "dingdan" + tradeResult.payResult.paySuccessOrders);
                if (!TextUtils.isEmpty(mOrderId)) {
                    Intent intent = new Intent(AliSdkWebViewProxyActivity.this, HomeOrderActivity.class);
                    startActivity(intent);
                }
                TipUtils.showToast(App.getInstance(), "支付成功", 1);
                finish();


            }
        }

        @Override
        public void onFailure(int errCode, String errMsg) {
            TipUtils.showToast(App.getInstance(), "支付取消", 2);
        }
    }

    //登录须重写onActivityResult方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CallbackContext.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if( mWebView!=null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        AlibcTradeSDK.destory();
        super.onDestroy();
    }


    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (isDestroyed()) return;
    }

}
